/**
 * create by young (young2f@outlook.com) on 2023/4/16
 */
'use strict';
const base = require('../base/serviceBase');
const _ = require('lodash');
const _stringUtils = require('../utils/stringUtils');
module.exports = class extends base {
  async register(body) {
    const { ctx } = this;
    delete body['cpassword'];
    const { userCode } = body;
    let code = userCode ? userCode : _stringUtils.getCode('HM');
    body.userCode = code;
    // if (body.userType === 'su') {
    //     const temp = await ctx.model.User.deleteMany({ userType: 'su' });
    // }
    const { username } = body;
    const res = await ctx.app.dbs.find('User', { username });
    if (res.length) {
      throw new Error('用户名已存在！');
    }
    const log = await ctx.app.dbs.insert('Log', { type: 'register', data: body });
    const result = await ctx.app.dbs.insert('User', body);
    return { status: 'ok', result };
  }

  async login(body) {
    const { username, password } = body;
    const { ctx } = this;
    const log = await ctx.app.dbs.insert('Log', { type: 'login', data: body });
    let user = await ctx.app.dbs.findOne('User', { username, isDeleted: false });
    if (!user) {
      throw new Error('用户名密码错误！');
    }
    const _user = _.clone(user);
    if (password !== _user.password) {
      throw new Error('用户名密码错误！');
    }

    delete _user['password'];
    const { tenantCode, roleCode, userType } = _user;

    if (userType === 'su') {
      // _user.renderUrl = '/tenant';
      return { status: 'ok', message: '超级管理员登录', result: _user };
    }

    const where = { tenantCode, roleCode };
    const role = await ctx.app.dbs.findOne('Role', where);
    if (!role) {
      throw new Error('员工没有设置角色！');
    }
    _user.role = role;

    const tenant = await ctx.app.dbs.findOne('Tenant', { tenantCode });

    // const renderUrl = _user.isSlave && role.menus.length > 1 ? role.menus[1] : '/desktop/index';
    const renderUrl = _user.isSlave ? '/selfService' : '/desktop/index';
    _user.tenant = tenant;
    _user.renderUrl = renderUrl;

    return { status: 'ok', result: _user };
  }

  async updateUser(body) {
    const { ctx } = this;
    const { username, tenantCode } = body;
    // const user = await ctx.model.User.findOne({ username, tenantCode });
    const user = await ctx.app.dbs.findOne('User', { username, tenantCode });
    if (!user) {
      throw new Error('该用户不存在或已被删除！');
    }
    const result = await ctx.app.dbs.updateOne('User', { username, tenantCode }, body);
    return { status: 'ok', result };
  }

  async updatePassword(body) {
    const { ctx } = this;
    const { username, password, oldPassword, tenantCode } = body;
    const user = await ctx.app.dbs.findOne('User', { username, tenantCode });
    if (!user) {
      throw new Error('该用户不存在或已被删除！');
    }
    if (user.password !== oldPassword) {
      throw new Error('旧密码错误！');
    }
    const result = await ctx.app.dbs.updateOne('User', { username, tenantCode }, {password});
    console.log('updata pass',result)
    return { status: 'ok', result };
  }

  async deleteUser(body) {
    const { ctx } = this;
    const { userCode, tenantCode } = body;
    const result = await ctx.app.dbs.deleteOne('User', { userCode, tenantCode });
    return { status: 'ok', result };
  }
  async resetPassword(body) {
    const { ctx } = this;
    const { username, tenantCode } = body;
    const user = await ctx.model.User.findOne({ username, tenantCode });
    if (!user) {
      throw new Error('该用户不存在或已被删除！');
    }
    const password = _stringUtils.getCryptoPassword('123456');
    const result = await ctx.model.User.updateOne({ username, tenantCode }, { password });
    return { status: 'ok', result };
  }
  async findUsersByPage(body) {
    const { ctx } = this;
    const { skip, limit, key, username, nickname, start, end, tenantCode } = body;
    const _key = key ? key : 'createdTs';
    delete body['skip'];
    delete body['limit'];
    delete body['start'];
    delete body['end'];
    const sort = {};
    sort[_key] = -1;
    if (start && end) {
      body[_key] = {
        $gt: new Date(moment(start)
          .valueOf()),
        $lt: new Date(moment(end)
          .valueOf())
      };
    }

    if (username) {
      body['username'] = { $regex: username };
    }
    if (nickname) {
      body['nickname'] = { $regex: nickname };
    }

    const users = await ctx.app.dbs.aggregate('User', [
      { $match: { ...body } },
      { $sort: { ...sort } },
      { $skip: skip },
      { $limit: limit },
    ]);

    const total = await ctx.app.dbs.count('User', { ...body });
    return { status: 'ok', result: { users, total } };
  }
};
